# @Project: diablo
# @File: multiple_quality_price
# @Time: 2023/10/10 15:56
# @User: Jolly
# @Email: jolly@007vin.com
"""
应对给定多种品质定价
"""

import datetime
# 小汽配2.0初始化商品定价
# 定价来源：客户提供的excel

import time
import threading
from queue import Queue

from io import BytesIO
from openpyxl import load_workbook
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure


class InitAgreementPrice:

    def __init__(self, agreement_excel_id, file_path):

        self.agreement_excel_id = agreement_excel_id
        self.file_path = f"./{file_path}.xlsx"

        start_time = time.time()

        # 初始化数据库连接
        # 2.0生产库
        self.diablo_conn_2_0 = self.get_mongo_connection("root", "aa123456", "192.168.191.175", "27017")

        # 执行任务
        self.task()

        print("========= 数据插入,共耗时:{}'s =========".format(round(time.time() - start_time, 3)))

    def get_mongo_connection(self, username, password, host, port):
        try:
            # 创建 MongoClient
            client = MongoClient(f"mongodb://{username}:{password}@{host}:{port}",
                                 maxPoolSize=150,
                                 minPoolSize=1,
                                 maxIdleTimeMS=30000,
                                 waitQueueTimeoutMS=2000)

            # 检测连接是否可用，如果连接不可用则抛出异常
            if not client:
                raise ConnectionFailure("从MongoDB连接池中获取连接失败！")

            return client

        except ConnectionFailure as e:
            # 处理连接失败的异常
            print(f"连接MongoDB失败: {e}")
            return None

    # 判断定价协议表是否已有对应数据，有的话就删除
    def check_agreement_exist(self, identify):

        check = False

        connection = self.diablo_conn_2_0

        try:
            if connection is not None:
                # 执行数据库操作
                db = connection["inventory_data"]
                conn = db["agreement_excel"]

                filter_dict = {
                    "identify": identify,
                    "agreement_excel_id": self.agreement_excel_id
                }
                docs_count = conn.count_documents(filter_dict)

                if docs_count > 0:
                    # 删除已有的
                    conn.delete_many(filter_dict)
                    # check = True

        except Exception as e:
            print("获取协议定价存在检测失败 - mongo：", e)
        finally:
            # 将连接放回连接池
            connection.close()

        return check

    # 通过oe号获取库存数据
    def get_stock_by_oe(self, oe, origin_quality):

        stocks_identify = []

        if oe:
            connection = self.diablo_conn_2_0

            try:
                if connection is not None:
                    # 执行数据库操作
                    db = connection["inventory_data"]
                    conn = db["ChangYuan_meta_stocks"]

                    filter_dict = {
                        "opid": oe,
                        "ori_quality": origin_quality,
                        "erp_uid": {"$in": ["T0000002_4TH0WP2OQ_T", "T0000002_4TH0WP2OQ_Z1"]}
                    }
                    docs = conn.find(filter_dict, {'identify': 1})

                    for doc in docs:
                        identify_dict = {'identify': doc.get("identify", "")}

                        stocks_identify.append(identify_dict)

            except Exception as e:
                print("获取用户库存数据identify失败 - mongo：", e)
            finally:
                # 将连接放回连接池
                connection.close()

        return stocks_identify

    # 写入数据
    def write_data(self, *args):

        oe = args[0]
        origin_quality = args[1]
        price = args[2]

        # 非数字字符串则返回
        if isinstance(price, str):
            if not price.isdigit():
                return

        stocks_identify = []

        # 因为oe可能会被去除0，所以补齐四次，四次都没有则记录
        for i in range(0, 5):

            # 通过oe号和原始品质查找库存记录，可能有多个
            stocks_identify = self.get_stock_by_oe(oe, origin_quality)

            if len(stocks_identify) == 0:

                if i != 4:
                    oe = "0" + oe
                    continue
                else:
                    with open("./not_hit.txt", "a") as file:
                        file.write(oe + "\n")

                    return
            else:
                break

        # 找到对应多条记录后，遍历获取identify，然后写入到agreement_price表中
        for identify in stocks_identify:

            # 返回的库存identify，再去查询agreement_price中，是否存在数据，存在则删除
            check = self.check_agreement_exist(identify.get("identify"))
            if not check:

                # 处理数字小数点
                if '.' in str(price):
                    integer_part, decimal_part = str(price).split('.')
                    decimal_part = decimal_part[:2]
                    price = float(f'{integer_part}.{decimal_part}')

                agreement_dict = {
                    "agreement_excel_id": self.agreement_excel_id,
                    "identify": identify.get("identify"),
                    "agreement_price": price,
                    "price_type": "customize",
                    "price_value": price,
                    "price_desc": f"¥ = {str(price)}",
                    "update_time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    "user_id": "0000000000000000003",  # 当前用户id
                    "price_user": "系统人工控价",  # 当前用户名
                    "price_time": datetime.datetime.now().strftime('%Y-%m-%d')
                }

                # 获取2.0MongoDB连接
                connection = self.diablo_conn_2_0

                try:
                    if connection is not None:
                        # 执行数据库操作
                        db = connection["inventory_data"]
                        conn = db["agreement_excel"]
                        conn.insert_one(dict(agreement_dict))

                except Exception as e:
                    print("写入2.0MongoDB数据库单据失败：", e)
                finally:
                    # 将连接放回连接池
                    connection.close()

    # 获取excel数据，生成器返回
    def get_excel_data(self):

        with open(self.file_path, "rb") as file:
            content = file.read()

        # 将内容转换为BytesIO对象
        bytesIO = BytesIO(content)

        # 加载工作簿
        book = load_workbook(bytesIO, read_only=True)

        # 获取活动工作表
        sheet = book.active

        previous = next(sheet.iter_rows(), None)
        for row in sheet.iter_rows():
            yield previous, False
            previous = row
        yield previous, True

    def get_all_excel_data(self):
        """
        获取全部excel
        """

        with open(self.file_path, "rb") as file:
            content = file.read()

        # 将内容转换为BytesIO对象
        bytesIO = BytesIO(content)

        # 加载工作簿
        book = load_workbook(bytesIO, read_only=True)

        # 获取活动工作表
        sheet = book.active

        return sheet.iter_rows()

    # 清空预设定价格协议记录
    def delete_exist_record(self):

        connection = self.diablo_conn_2_0

        try:
            if connection is not None:
                # 执行数据库操作
                db = connection["inventory_data"]
                conn = db["agreement_excel"]

                filter_dict = {
                    "price_type": "customize",
                    "agreement_excel_id": 33
                }
                conn.delete_many(filter_dict)

        except Exception as e:
            print("删除已有价格协议数据identify失败 - mongo：", e)
        finally:
            # 将连接放回连接池
            connection.close()

    # 删除重复项
    def delete_one_of_same(self):

        connection = self.diablo_conn_2_0

        try:
            if connection is not None:
                # 执行数据库操作
                db = connection["inventory_data"]
                conn = db["agreement_excel"]

                filter_dict = {
                    "price_type": "customize",
                    "agreement_excel_id": 33
                }

                # 查询所有记录，遍历每一个是否有重复项
                docs = conn.find(filter_dict, {'identify': 1})

                for doc in docs:
                    identify = doc.get("identify", "")

                    identify_docs_count = conn.count_documents({"identify": identify, "price_type": "customize", "agreement_excel_id": 33})

                    if identify_docs_count > 1:
                        # 循环删除多余记录
                        for i in range(0, identify_docs_count - 1):
                            conn.delete_one({"identify": identify, "price_type": "customize", "agreement_excel_id": 33})

        except Exception as e:
            print("删除已有价格协议数据identify失败 - mongo：", e)
        finally:
            # 将连接放回连接池
            connection.close()

    def fixed_same_quality(self, all_data):
        """
        因为存在多仓库，oe和品质相同，价格不同的数据，需要处理只保留最大的
        """

        data_list = []

        for row in all_data:
            oe = str(row[0].value)
            origin_quality = row[1].value
            price = row[2].value

            # oe去除空格
            oe = oe.strip()
            oe = oe.replace(' ', '')

            data_list.append({
                "oe": oe,
                "origin_quality": origin_quality,
                "price": price
            })

        # 获取最大的
        result = {}

        for item in data_list:
            key = (item["oe"], item["origin_quality"])
            if key not in result or item["price"] > result[key]["price"]:
                result[key] = item

        final_result = list(result.values())

        # print(final_result)

        return final_result

    # 任务执行
    def task(self):
        q = Queue(maxsize=100)  # 设定最大队列数和线程数

        # self.delete_exist_record()

        # self.delete_one_of_same()

        count = 1

        all_data = self.get_all_excel_data()

        # 因为存在多仓库，oe和品质相同，价格不同的数据，需要处理只保留最大的
        fixed_data = self.fixed_same_quality(all_data)

        for row in fixed_data:
            oe = row.get("oe")
            origin_quality = row.get("origin_quality")
            price = row.get("price")

            t = threading.Thread(target=self.write_data, args=(oe, origin_quality, price))
            q.put(t)
            if q.full() == True:
                thread_list = []
                while q.empty() == False:
                    t = q.get()
                    thread_list.append(t)
                    t.start()
                for t in thread_list:
                    t.join()

            print("当前写入数：", count, " 零件为：", oe, ", 品质为：", origin_quality, ", 价格为：", price)

            count += 1

        # 处理残余队列数据
        thread_list = []
        while q.empty() == False:
            t = q.get()
            thread_list.append(t)
            t.start()
        for t in thread_list:
            t.join()


if __name__ == "__main__":
    # file_list = ["hongde2023101002", "hongde2023101003", "hongde2023101101", "hongde2023101102", "hongde2023101201",
    #              "hongde2023101202", "hongde2023101301", "hongde2023101401", "hongde2023101501", "hongde2023101601",
    #              "hongde2023101901", "hongde2023101902", "hongde2023101903", "hongde2023102301", "hongde2023102302",
    #              "hongde2023102401", "hongde2023102501", "hongde2023102502", "hongde2023102601", "hongde2023102602",
    #              "hongde2023102701", "hongde2023102702", "hongde2023102901", "hongde2023103101", "hongde2023110601",
    #              "hongde2023111301", "hongde2023112501", "hongde2023120501"]
    #
    # for file_path in file_list:
    #     print(f"当前刷写的是-------------------{file_path}----------------------------")
    #     InitAgreementPrice(33, file_path)

    InitAgreementPrice(33, "hongde2023120501")

